import React, { useEffect, useState, useRef } from "react";
import {
  Button,
  Table,
  Space,
  Tag,
  Popconfirm,
  Drawer,
  Input,
  Select,
  Tree,
  Modal
} from "antd";
import {
  getAdminListInterface,
  delAdminInterface,
  addAdminInterface,
  updateAdminInterface,
} from "@/api/admin";
import {
  EditOutlined,
  DeleteOutlined,
  InfoCircleOutlined,
} from "@ant-design/icons";
import menus from "@/routers/menus";
import usePagination from "@/hooks/usePagination";
export default function AdminList() {
  // 表格数据来源数组
  const [dataSource, setDataSource] = useState([]);
  // 翻页序号标识
  const flagRef = useRef(true);
  // 分页自定义hook
  const pagination = usePagination();
  // 选中的adminid数组
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  // Drawer开关控制
  const [open, setOpen] = useState(false);
  // 定义初始化账号信息
  const [adminname, setAdminname] = useState("");
  const [password, setPassword] = useState("");
  const [role, setRole] = useState(1);
  const [checkedKeys, setCheckedKeys] = useState(["/",'/setting']);

  // 设置modal显示/隐藏
  const [isModalOpen, setIsModalOpen] = useState(false);

  const columns = [
    {
      title: "序号",
      // TODO 这里可以用 _ 来表示占位不使用的参数
      render(_, __, index) {
        // 判断删除的是否为最后一页页最后一条数据
        dataSource?.length === pagination.pageSize * (pagination.current - 1) &&
          (flagRef.current = false);
        return (
          pagination.pageSize *
            (flagRef.current
              ? pagination.current - 1
              : pagination.current - 2) +
          index +
          1
        );
      },
    },
    {
      title: "用户名",
      dataIndex: "adminname",
    },
    {
      title: "权限",
      dataIndex: "role",
      render(_, data) {
        return data.role === 1 ? (
          <Tag bordered={false} color="green">
            普通管理员
          </Tag>
        ) : (
          <Tag bordered={false} color="red">
            超级管理员
          </Tag>
        );
      },
    },
    {
      title: "操作",
      render(_, data) {
        return (
          <Space>
            <Button type="primary" onClick={() => {
              // todo

              setIsModalOpen(true);
              // 给字段赋值
              setAdminname(data.adminname);
              setPassword(data.password)
              setRole(data.role);
              setCheckedKeys(data.checkedKeys);
            }} icon={<EditOutlined />} />
            <Popconfirm
              title="不可逆操作!"
              description="你确定要删除该条数据吗?"
              icon={<InfoCircleOutlined style={{ color: "red" }} />}
              onConfirm={async () => {
                await delAdminInterface({ adminid: data.adminid });
                getAdminListData();
              }}
            >
              <Button type="primary" danger icon={<DeleteOutlined />} />
            </Popconfirm>
          </Space>
        );
      },
    },
  ];
  // 清除表单内容
  const clearAdminData = () => { 
    setAdminname('')
    setPassword('')
    setRole(1)
    setCheckedKeys(['/','/setting'])
  }
  // 获取管理员列表数据
  const getAdminListData = () => {
    getAdminListInterface().then((res) => {
      setDataSource(res?.data?.data);
    });
  };
  // 页面第一次渲染,加载管理员列表
  useEffect(() => {
    getAdminListData();
  }, []);
  // 监测是否翻页,对序号标识进行判断修改
  useEffect(() => {
    flagRef.current = true;
  }, [pagination]);

  // 选中数据变化时触发
  const onSelectChange = (newSelectedRowKeys) => {
    setSelectedRowKeys(newSelectedRowKeys);
  };
  // 选中的某些数据
  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };
  // 处理删除选中的方法
  const handleDelSelected = () => {
    const DELETE_ARR = [];
    selectedRowKeys.forEach((adminid) => {
      DELETE_ARR.push(delAdminInterface({ adminid }));
    });
    Promise.allSettled(DELETE_ARR).then(() => {
      getAdminListData();
    });
  };
  // 关闭添加管理员抽屉方法
  const onClose = () => {
    setOpen(false);
  };
  // 添加管理员
  const addAdminDrawer = () => {
    clearAdminData()
    setOpen(true);
  };
  // 获取到treeData
  const getTreeData = (menus) => {
    const TREE_DATA_ARR = []
    menus.forEach((menu) => {
      let TREE_DATA_OBJ = {};
      if (menu.children) {
        TREE_DATA_OBJ = {
          key: menu.key,
          title: menu.label,
          children: getTreeData(menu.children),
        };
      } else {
        TREE_DATA_OBJ = {
          key: menu.key,
          title: menu.label
        };
      }
      TREE_DATA_ARR.push(TREE_DATA_OBJ);
    });
    return TREE_DATA_ARR
  };
  const treeData = getTreeData(menus)

  // 添加管理员接口相关调用
  const handleAddAdmin = () => { 
    addAdminInterface({ adminname, password, role, checkedKeys }).then(() => { 
      setOpen(false)
      getAdminListData();
    })
  }

  // 更新管理员接口调用
  const handleUpdateAdmin = () => {
    updateAdminInterface({ adminname, password, role, checkedKeys }).then(() => {
      setIsModalOpen(false)
      getAdminListData()
    })
  }
  return (
    <Space direction="vertical" style={{ width: "100%" }}>
      <Space>
        <Button type="primary" onClick={addAdminDrawer}>
          添加管理员
        </Button>
        {selectedRowKeys.length > 0 && (
          <Button type="primary" danger onClick={handleDelSelected}>
            删除选中
          </Button>
        )}
      </Space>
      <Table
        style={{ width: "100%" }}
        rowSelection={rowSelection}
        rowKey={(record) => record.adminid}
        dataSource={dataSource}
        columns={columns}
        pagination={pagination}
      />
      <Drawer
        title="添加管理员"
        placement="right"
        onClose={onClose}
        open={open}
      >
        <Space direction="vertical">
          <Input
            placeholder="用户名"
            value={adminname}
            onChange={(e) => setAdminname(e.target.value)}
          />
          <Input
            placeholder="密码"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
          />
          <Select
            style={{ width: "100%" }}
            value={role}
            onChange={(value) => setRole(value)}
          >
            <Select.Option value={1}>管理员</Select.Option>
            <Select.Option value={2}>超级管理员</Select.Option>
          </Select>
          选择管理员的权限:
          <Tree
            checkable
            treeData={treeData}
            checkedKeys={checkedKeys}
            onCheck={(checkedKeysValue) => {
              setCheckedKeys(checkedKeysValue);
            }}
            defaultExpandAll 
          />
          <Button type="primary" onClick={handleAddAdmin}>
            添加管理员
          </Button>
        </Space>
      </Drawer>

      {/*显示编辑管理员的Modal弹窗面板*/}
      <Modal
        footer={null}
        title="编辑管理员"
        open={isModalOpen}
        onCancel={() => {
          setIsModalOpen(false);
          // 清空数据
          setAdminname("");
          setPassword("");
          setRole(1);
          setCheckedKeys(["/"]);
        }}
      >
        <Space direction="vertical" style={{ display: "flex" }}>
          <Input disabled placeholder="账户名" value={adminname} />
          <Select
            style={{ width: "200px" }}
            value={role}
            onChange={(value) => setRole(value)}
          >
            <Select.Option value={1}>管理员</Select.Option>
            <Select.Option value={2}>超级管理员</Select.Option>
          </Select>
          选择管理员权限：
          <Tree
            checkable
            treeData={treeData}
            checkedKeys={checkedKeys}
            onCheck={(checkedKeysValue) => {
              // 点击每一项就会触发
              setCheckedKeys(checkedKeysValue);
            }}
            defaultExpandAll // 展开所有的
          />
          <Button type="primary" onClick={handleUpdateAdmin}>
            更新管理员
          </Button>
        </Space>
      </Modal>
    </Space>
  );
}
